package com.yx.cloud.fragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.aliyun.aligeniessp_1_0.models.AuthLoginWithThirdUserInfoResponseBody;
import com.aliyun.aligeniessp_1_0.models.EcologyOpennessAuthenticateResponseBody;
import com.aliyun.aligeniessp_1_0.models.ListDeviceByUserIdResponseBody;
import com.aliyun.alink.business.devicecenter.api.add.DeviceInfo;
import com.aliyun.alink.business.devicecenter.api.discovery.LocalDeviceMgr;
import com.google.gson.Gson;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.sdk.yugong.YuGongConstants;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanParam;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.activity.AddEquipmentActivity;
import com.yx.cloud.activity.MainActivity2;
import com.yx.cloud.activity.MainBottomTabActivity;
import com.yx.cloud.activity.SelectWIFIActivity;
import com.yx.cloud.adapter.AddDevice_BluetoothListAdapter;
import com.yx.cloud.adapter.DeviceListDataAdapter;
import com.yx.cloud.bean.tmall.AuthorizedLogin;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.network.ble.BluetoothModel;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.yx.cloud.product.laser.tuyapublic.BluetoothScanDeviceBean;
import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
import com.yx.cloud.utils.AliHttpRequest_Runnable;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.SharedPreferencesList;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.BounceLayout;
import com.yx.cloud.view.DefaultHeader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class DeviceFragment extends Fragment {
    public List<Robot> newDeviceList;
    public int count = 0;
    public List<Boolean> selectList;
    private View view;
    private RecyclerView deviceListData_rv, mBluetoothDeviceList;
    private BounceLayout bl_device;
    private FrameLayout fl_device_container;
    private DeviceListDataAdapter listDataAdapter;
    private MainBottomTabActivity activity;
    private ImageView ivDeleteDeviceFinishIcon, ivBottomTabAddDeviceIcon;
    private RelativeLayout rlDeleteDeviceFinishTitle, rlDeviceTitle;
    private TextView ivDeleteDeviceCount;
    private LottieAnimationView lottieAnimationView;
    private List<BluetoothScanDeviceBean> scanBleDeviceList = new ArrayList<>();//蓝牙扫描结果存储
    private DeviceListHandler handler;
    private BluetoothModel model;
    private boolean doesItExist = false;
    private AddDevice_BluetoothListAdapter bleAdapter;
    private AliHttpRequest_Runnable aLi_interface = new AliHttpRequest_Runnable();
    private int authorized = 0, authentication = 0, AligenieUserInfo = 0, tmallDeviceList = 0;
    private List<ListDeviceByUserIdResponseBody.ListDeviceByUserIdResponseBodyResult> tmall_result;
    private LoadProgressDialog loadProgressDialog;
    private String device_type;
    private boolean isX5Device = false;
    private BluetoothScanDeviceBean bsb;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        view = inflater.inflate(R.layout.device_fragment_item, null);
        activity = (MainBottomTabActivity) getActivity();
        handler = new DeviceListHandler(this);
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        LogUtils.i(" 设备列表 fragment-----------initView");
        deviceListData_rv = view.findViewById(R.id.deviceListData);
        rlDeleteDeviceFinishTitle = view.findViewById(R.id.rl_deleteDeviceFinish_title);
        rlDeviceTitle = view.findViewById(R.id.rl_device_title);
        ivDeleteDeviceFinishIcon = view.findViewById(R.id.iv_deleteDeviceFinishIcon);
        ivDeleteDeviceCount = view.findViewById(R.id.iv_deleteDeviceCount);
        ivBottomTabAddDeviceIcon = view.findViewById(R.id.iv_bottom_tab_add_device_icon);
        lottieAnimationView = view.findViewById(R.id.lottieAnimationView);
        mBluetoothDeviceList = view.findViewById(R.id.bluetoothDeviceList);

        bl_device = view.findViewById(R.id.bl_device);
        fl_device_container = view.findViewById(R.id.fl_device_container);
        bl_device.setBounceHandler(new NormalBounceHandler(), deviceListData_rv);//设置滚动冲突的控制类
        bl_device.setEventForwardingHelper((downX, downY, moveX, moveY) -> true);
        bl_device.setHeaderView(new DefaultHeader(getActivity()), fl_device_container);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        bl_device.setBounceCallBack(new BounceCallBack() {
            @Override
            public void startRefresh() {
                scanBleDeviceList.clear();
                if (bleAdapter != null) {
                    bleAdapter.notifyDataSetChanged();
                }
                AppContext.getAccountService().getDeviceList();
            }

            @Override
            public void startLoadingMore() {
                //requestNotification(messageAdapter.getCount(), 10, false);
            }
        });
    }

    private void initData() {
        newDeviceList = new ArrayList<>();
        selectList = new ArrayList<>();
        listDataAdapter = new DeviceListDataAdapter(getActivity(), newDeviceList);
        deviceListData_rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        deviceListData_rv.setAdapter(listDataAdapter);
        listDataAdapter.setChecked(new DeviceListDataAdapter.onChecked() {
            @Override
            public void CheckedChanged(int position, boolean isChecked, CompoundButton buttonView) {
                if (isChecked) {
                    count++;
                } else {
                    count--;
                }
                LogUtils.i(position + " 设备列表 选中状态-----------" + isChecked + "  " + count + " size " + selectList.size());
                selectList.set(position, isChecked);
                ivDeleteDeviceCount.setText(getString(R.string.H_Delete_title).replace("{X}", count + ""));
            }
        });
        listDataAdapter.setOnItemClickListener(new DeviceListDataAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                LogUtils.i("设备列表 点击-----------" + bl_device.currentRefreshing);
                Robot robot = newDeviceList.get(position);
                if (robot != null) {
                    boolean online = robot.isOnline();
                    if (online) {
                        if (!bl_device.currentRefreshing && !listDataAdapter.isShowSelect()) {
                            String productId = robot.getProductId();
                            if ("x5-max".equals(productId)) {
                                //这里如果是x5的设备把基站的设备id存入，为了设置基站颜色图片
                                String tmalDeviceId = robot.getTmalDeviceId();
                                List<String> tmallDevice = new ArrayList<>();
                                if (tmalDeviceId == null || tmalDeviceId.equals("")) {
                                    //X5 MAX不进行基站配网所以没有基站的设备id,那就使用机器的设备id进行标记
                                    tmallDevice.add(robot.getDeviceId());
                                } else {
                                    tmallDevice.add(tmalDeviceId);
                                }
                                SharedPreferencesList.switchRobotPictureX5(activity, "add", "white", tmallDevice, "连接设备");
                            }
                            AppContext.get().connectDevice(newDeviceList.get(position));//切换设备连接
                            AppContext.getProductService().sendTimeZoneToDevice();
                            MyApplication.recvActive = true;
                            Intent_utils.enterIntent(activity, MainActivity2.class);
                            if (model != null) {
                                model.stopScanBle();
                            }
                            LocalDeviceMgr.getInstance().stopDiscovery();//停止蓝牙扫描

                        }
                    } else {
                        activity.deviceOffLineHintDialog();
                    }
                }
            }

            @Override
            public void onLongClick(View view, int position) {
                LogUtils.i("设备列表 长按------------" + bl_device.currentRefreshing);
                if (!bl_device.currentRefreshing && !listDataAdapter.isShowSelect()) {
                    rlDeviceTitle.setVisibility(View.GONE);
                    rlDeleteDeviceFinishTitle.setVisibility(View.VISIBLE);
                    activity.rg.setVisibility(View.GONE);
                    activity.mBottomTabRlDelete.setVisibility(View.VISIBLE);
                    ivDeleteDeviceCount.setText("已选中" + count + "个");
                    listDataAdapter.showSelect(true);
                }
            }

            @Override
            public void setRechargeCommClick(int position) {
                LogUtils.i("设备列表 回充------------");
                Robot robot = newDeviceList.get(position);
                int state = robot.getRobotStatus().getWorkState();
                int mode = robot.getRobotStatus().getWorkMode();
                if (state == RobotStatus.STATE_CHARGING) {
                    ToastUtil.showShort(getActivity(), R.string.H_State_Charging);
                } else if (state == RobotStatus.STATE_WORKING && mode == RobotStatus.MODE_RECHARGE) {
                    robot.pauseRecharge();
                } else if (state == RobotStatus.STATE_PAUSE && mode == RobotStatus.MODE_RECHARGE) {
                    robot.continueRecharge();
                } else {
                    robot.startRecharge();
                }
                listDataAdapter.updateData(newDeviceList);
            }

            @Override
            public void setCleanCommClick(int position) {
                LogUtils.i("设备列表 清扫------------");
                Robot robot = newDeviceList.get(position);
                int state = robot.getRobotStatus().getWorkState();
                int mode = robot.getRobotStatus().getWorkMode();
                if (state == RobotStatus.STATE_WORKING && mode != RobotStatus.MODE_RECHARGE) {
                    robot.pauseSweep();
                } else if (state == RobotStatus.STATE_PAUSE && mode != RobotStatus.MODE_RECHARGE) {
                    robot.continueSweep(null);
                } else {
                    CleanParam cleanParam = new CleanParam();
                    cleanParam.setType(RobotStatus.MODE_AUTO_CLEAN);
                    robot.startSweep(cleanParam);
                }
                listDataAdapter.updateData(newDeviceList);
            }
        });

        ivDeleteDeviceFinishIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlDeviceTitle.setVisibility(View.VISIBLE);
                rlDeleteDeviceFinishTitle.setVisibility(View.GONE);
                activity.rg.setVisibility(View.VISIBLE);
                activity.mBottomTabRlDelete.setVisibility(View.GONE);
                listDataAdapter.showSelect(false);
            }
        });

        ivBottomTabAddDeviceIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                model.stopScanBle();
                Intent_utils.enterIntent(getActivity(), AddEquipmentActivity.class);
            }
        });


        bleAdapter = new AddDevice_BluetoothListAdapter(activity, scanBleDeviceList);
        mBluetoothDeviceList.setLayoutManager(new LinearLayoutManager(activity));
        mBluetoothDeviceList.setAdapter(bleAdapter);
        bleAdapter.setOnItemClickListener(new AddDevice_BluetoothListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                SharedPrefsUtil.putValue(activity, "ROBOT_SERIES", "robot_series", "bluetooth");//给配网失败后返回使用
                BluetoothScanDeviceBean deviceBean = scanBleDeviceList.get(position);
                String source = deviceBean.getSource();//区分蓝牙扫描出来的设备 是X5 基站还是其他机型的
                String deviceType = ProductConfigConstants.getNetworkDeviceType(deviceBean.getName());//根据选择的机型设置设备类型
                if ("yugong".equals(source)) {
                    Intent select = new Intent(activity, SelectWIFIActivity.class);
                    select.putExtra("network", "bluetooth");
                    select.putExtra("source", "other");
                    select.putExtra("bluetoothData", deviceBean);
                    select.putExtra("device_type", deviceType);//设备型号
                    startActivity(select);
                }
            }
        });

        loadProgressDialog = new LoadProgressDialog(activity);
        loadProgressDialog.show();

        AppContext.get().disconnectDevice();//获取设备列表前 断开设备连接
        AppContext.getAccountService().getDeviceList();
    }

    @Override
    public void onResume() {
        super.onResume();
        scanBleDeviceList.clear();
        if (bleAdapter != null) {
            bleAdapter.notifyDataSetChanged();
        }
        checkTmallAccountIsValid("init");
        startScan();//蓝牙扫描
        handler.sendEmptyMessage(DeviceListHandler.MSG_REQUEST_DEVICE_STATUS);
    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtils.i(" 设备列表 fragment-----------onPause");
        handler.removeMessages(DeviceListHandler.MSG_REQUEST_DEVICE_STATUS);
        handler.removeMessages(DeviceListHandler.MSG_REQUEST_TMALL_AUTH);
        model.stopScanBle();
        LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
    }


    @SuppressLint("MissingPermission")
    private void startScan() {
        LogUtils.i(" 设备列表 fragment-----------start Scan");
        AliGenieSdk.tmallBluetoothScan(activity);//阿里 开始蓝牙扫描
        model = BluetoothModel.getInstance();
        model.startScanBle(new BluetoothModel.BLEScanCallback() {
            @Override
            public void onDeviceFind(BluetoothDevice device) {
                String name = device.getName();
                if (name == null || (!name.contains("INXNI") && !name.contains("ROBOT-yx"))) {
                    return;
                }
                if (name.contains("X5Max")) {
                    return;
                }
                LogUtils.i("--------------------------------扫描到了: " + name + " ," + device.getAddress());
                //model.stopScanBle();
                Event.newBuilder().type(Event.MESSAGE_TYPE_TUYA_BLUETOOTH_SCAN).content(device).send();
            }
        });
    }


    @SuppressLint("MissingPermission")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_DEVICE_LIST:
                //获取设备列表
                // 加载完数据设置为不加载状态，将加载进度收起来
                bl_device.setRefreshCompleted();
                if (loadProgressDialog != null && loadProgressDialog.isShowing()) {
                    loadProgressDialog.dismiss();
                }
                if (event.isResult()) {
                    newDeviceList.clear();
                    selectList.clear();
                    newDeviceList = (List<Robot>) event.getContent();
                    LogUtils.i(newDeviceList.size() + " : 获取设备列表 : " + new Gson().toJson(newDeviceList));
                    if (newDeviceList.size() == 0) {
                        deviceListData_rv.setVisibility(View.GONE);
                        lottieAnimationView.setVisibility(View.VISIBLE);
                    } else {
                        for (int i = 0; i < newDeviceList.size(); i++) {
                            String productId = newDeviceList.get(i).getProductId();
                            LogUtils.i("获取设备列表 productId : " + productId);
                            if (productId.equals("x5-max")) {
                                isX5Device = true;
                            }
                        }
                        if (isX5Device && !"".equals(INXNIConstant.USER_ID)) {//有X5的机器与账号不为空
                            LogUtils.i(" 开始获取天猫设备 ");
                            checkTmallAccountIsValid("device_list");//判断天猫账号是否在有效期
                        } else {
                            handleDeviceList(newDeviceList, "没有x5机器");
                        }
                    }
                } else {
                    deviceListData_rv.setVisibility(View.GONE);
                    lottieAnimationView.setVisibility(View.VISIBLE);
                }
                break;
            case Event.MESSAGE_TYPE_AUTHORIZED_LOGIN:
                //去 授权登录()检测
                if (event.isResult()) {
                    AuthLoginWithThirdUserInfoResponseBody body = (AuthLoginWithThirdUserInfoResponseBody) event.getContent();
                    Integer code = body.code;
                    LogUtils.i("授权登录 结果返回  :" + new Gson().toJson(body));
                    if (code == 5140001) {
                        //要去从新注册
                        INXNIConstant.SESSION_ID = body.getDataObj().getSessionId();
                        if (isX5Device && !"".equals(INXNIConstant.USER_ID)) {
                            handleDeviceList(newDeviceList, "666666");
                        }
                    } else {
                        //登录成功，
                        String extra = (String) event.getExtra();
                        String accessToken = body.getResult().getLoginStateAccessToken();
                        INXNIConstant.ACCESS_TOKEN = accessToken;
                        SharedPrefsUtil.putValue(activity, "TMALL_ACCESS_TOKEN", "tmall_access_token", INXNIConstant.ACCESS_TOKEN);
                        //获取鉴权成功后,获取有效时间
                        Long expiredTimeLong = body.getResult().getExpiredTimeLong();
                        SharedPrefsUtil.putValue(activity, "TMALL_AUTHENTICATION_TIME", "tmall_authentication_time", expiredTimeLong);

                        //登录成功后，去鉴权拿userOpenId
                        AuthorizedLogin authorizedLogin = new AuthorizedLogin();
                        authorizedLogin.setAccessToken(accessToken);
                        authorizedLogin.setAuthSource(extra);
                        aLi_interface.initialization("authentication", authorizedLogin);
                    }
                } else {
                    authorized++;
                    if (authorized < 3) {
                        AuthorizedLogin auth_login = new AuthorizedLogin();
                        auth_login.setSceneCode(INXNIConstant.SCENE_CODE);
                        auth_login.setThirdUserType(INXNIConstant.THIRUSER_TYPE);
                        auth_login.setThirdUserIdentifier(INXNIConstant.USER_ID);//INXNIConstant.USER_ID INXNIConstant.THIRUSER_IDENTIFIER
                        aLi_interface.initialization("auth_login", auth_login);
                    }
                }
                break;
            case Event.MESSAGE_TYPE_ACCESS_TOKEN_AUTHENTIATION:
                //鉴权结果返回
                if (event.isResult()) {
                    EcologyOpennessAuthenticateResponseBody body = (EcologyOpennessAuthenticateResponseBody) event.getContent();
                    LogUtils.i("  鉴权AccessToken是否有效 结果返回  :" + new Gson().toJson(body));
                    Integer code = body.getCode();
                    String message = body.getMessage();
                    String extra = (String) event.getExtra();
                    if (200 == code && "OK".equals(message)) {
                        //鉴权成功
                        EcologyOpennessAuthenticateResponseBody.EcologyOpennessAuthenticateResponseBodyResult result = body.getResult();
                        INXNIConstant.USER_OPEN_ID = result.getUserOpenId();
                        INXNIConstant.ENCODETYPE = result.getEncodeType();
                        INXNIConstant.ENCODEKEY = result.getEncodeKey();
                        INXNIConstant.SCENE_CODE = result.getSceneCode();
                        SharedPrefsUtil.putValue(activity, "TMALL_USER_OPEN_ID", "tmall_user_open_id", INXNIConstant.USER_OPEN_ID);
                        String tmallUserInfo = SharedPrefsUtil.getValue(activity, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", "");
                        LogUtils.i(extra + " : 获取天猫用户信息 " + tmallUserInfo);
                        if (tmallUserInfo.equals("")) {
                            //获取天猫用户信息
                            AuthorizedLogin authorizedLogin = new AuthorizedLogin();
                            authorizedLogin.setAccessToken(INXNIConstant.ACCESS_TOKEN);
                            authorizedLogin.setAuthSource(extra);
                            aLi_interface.initialization("aligenie_user_info", authorizedLogin, activity);
                        } else {
                            if (extra.equals("device_list")) {
                                //获取天猫设备列表
                                aLi_interface.initialization("getUserDevice_list", null);
                            }
                        }
                    } else {
                        //鉴权失败
                        authentication++;
                        if (authentication < 3) {
                            AuthorizedLogin authorizedLogin = new AuthorizedLogin();
                            authorizedLogin.setAccessToken(INXNIConstant.ACCESS_TOKEN);
                            authorizedLogin.setAuthSource(extra);
                            aLi_interface.initialization("authentication", authorizedLogin);
                        } else {
                            if (newDeviceList.size() > 0) {
                                LogUtils.i("鉴权失败");
                                handleDeviceList(newDeviceList, "99999");
                            }
                            SharedPrefsUtil.putValue(activity, "TMALL_ACCESS_TOKEN", "tmall_access_token", "");
                        }
                    }
                }
                break;
            case Event.MESSAGE_TYPE_GET_ALIGENIE_USER_INFO:
                //获取三方绑定的精灵账号信息
                if (event.isResult()) {
                    String extra = (String) event.getExtra();
                    String nickname = (String) event.getContent();
                    INXNIConstant.TMALL_USER_NICK_NAME = nickname;
                    LogUtils.i(" 获取三方绑定的精灵账号信息 结果返回  :" + nickname);
                    SharedPrefsUtil.putValue(activity, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", nickname);
                    if (extra.equals("device_list")) {
                        //获取天猫设备列表
                        aLi_interface.initialization("getUserDevice_list", null);
                    }
                } else {
                    AligenieUserInfo++;
                    if (AligenieUserInfo < 3) {
                        //获取关联的天猫账号信息
                        aLi_interface.initialization("aligenie_user_info", null);
                    }
                }
                break;
            case Event.MESSAGE_TYPE_GET_USER_DEVICE_LIST:
                //获取天猫账号下的设备
                if (event.isResult()) {
                    tmall_result = (List<ListDeviceByUserIdResponseBody.ListDeviceByUserIdResponseBodyResult>) event.getContent();
                    LogUtils.i("天猫账号下的设备 列表 ： " + new Gson().toJson(tmall_result));
                    if (tmall_result.size() > 0) {
                        //保存天猫的设备id
                        AppContext.get().tmall_deviceId.clear();
                        for (int i = 0; i < tmall_result.size(); i++) {
                            AppContext.get().tmall_deviceId.add(tmall_result.get(i).deviceOpenId);
                        }
                    }
                    if (newDeviceList.size() > 0) {
                        handleDeviceList(newDeviceList, "8888");
                    }
                } else {
                    tmallDeviceList++;
                    if (tmallDeviceList < 3) {
                        //获取天猫设备列表
                        aLi_interface.initialization("getUserDevice_list", null);//获取天猫账号下设备
                    } else {
                        if (newDeviceList.size() > 0) {
                            handleDeviceList(newDeviceList, "2222");
                        }
                    }
                }
                break;
            case Event.MESSAGE_TYPE_TUYA_BLUETOOTH_SCAN:
                //蓝牙扫描
                BluetoothDevice device = (BluetoothDevice) event.getContent();
                @SuppressLint("MissingPermission") String name = device.getName();
                LogUtils.i(name + " ," + device.getAddress() + " yugong Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(device));
                doesItExist = false;
                if (scanBleDeviceList.size() > 0) {
                    for (int i = 0; i < scanBleDeviceList.size(); i++) {
                        if (device.getAddress().equals(scanBleDeviceList.get(i).getAddress())) {
                            doesItExist = true;
                        }
                    }
                }
                if (!doesItExist) {
                    scanDataPackage("yugong", device, null);
                    bleAdapter.notifyDataSetChanged();
                }
                break;
            case Event.MESSAGE_TYPE_DELETE_EQUIPMENT:
                if (event.isResult()) {
                    AppContext.getAccountService().getDeviceList();
                } else {
                    ToastUtil.showShort(getActivity(), R.string.U_T_Delete_No);
                }
                break;
            case Event.MSG_ROBOT_STATE:
                listDataAdapter.notifyDataSetChanged();
                break;
            case Event.MESSAGE_TYPE_DEVICE_RESET_LIST:
                //机器是否重置,TODO:这里不走广播因为当界面在设备列表时，不进行设备连接直接刷新设备列表
                //LogUtils.i("机器按键重置了vvvvv ：广播了 ");
                if (event.isResult()) {
                    if (!MyApplication.recvActive) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        boolean factory_reset = (boolean) event.getContent();
                        LogUtils.i("机器按键重置了bbbb ：广播了" + factory_reset);
                        AppContext.getAccountService().getDeviceList();
                    }
                }
                break;
        }
    }

    private void handleDeviceList(List<Robot> deviceLsit, String tag) {
        LogUtils.i("handleDeviceList > " + tag);
        AppContext.get().setDeviceList(deviceLsit);
        for (int i = 0; i < deviceLsit.size(); i++) {
            //删除设备使用
            selectList.add(false);
        }
        lottieAnimationView.setVisibility(View.GONE);
        deviceListData_rv.setVisibility(View.VISIBLE);

        listDataAdapter.updateData(deviceLsit);
        /**
         * 切换机器人图片保存对应的key
         */
        SharedPreferencesList.switchRobotPicture(activity, "add", "white", AppContext.get().getDeviceList(), "11111");
        //SharedPreferencesList.switchRobotPictureX5(activity, "add", "white", AppContext.get().tmall_deviceId, "11111 x5");
        LogUtils.i("切换机器人图片 : " + AppContext.get().getDeviceList().size());
    }

    public void requestDeviceListStatus() {
        for (int i = 0; i < newDeviceList.size(); i++) {
            Robot device = newDeviceList.get(i);
            device.getDeviceState();
        }
        handler.sendEmptyMessageDelayed(DeviceListHandler.MSG_REQUEST_DEVICE_STATUS, YuGongConstants.DURATION_REQUEST_DATA);
    }

    @SuppressLint("MissingPermission")
    private void scanDataPackage(String source, BluetoothDevice bean, DeviceInfo deviceInfo) {
        bsb = new BluetoothScanDeviceBean();
        bsb.setSource("yugong");
        bsb.setAddress(bean.getAddress());
        bsb.setName(bean.getName());
        scanBleDeviceList.add(bsb);
    }

    /**
     * 判断天猫账号是否在有效期
     */
    public void checkTmallAccountIsValid(String authSource) {
        //使用的是登录的获取的token
        if (!"".equals(INXNIConstant.USER_ID)) {
            String mAccessToken = SharedPrefsUtil.getValue(activity, "TMALL_ACCESS_TOKEN", "tmall_access_token", "");
            INXNIConstant.ACCESS_TOKEN = mAccessToken;
            LogUtils.i(authSource + " : ggggggg mAccessToken aa : " + mAccessToken);
            INXNIConstant.USER_OPEN_ID = SharedPrefsUtil.getValue(activity, "TMALL_USER_OPEN_ID", "tmall_user_open_id", "");
            long beginTime = SharedPrefsUtil.getValue(activity, "TMALL_AUTHENTICATION_TIME", "tmall_authentication_time", 0L);
            LogUtils.i(beginTime + " ： 上次存储的 天猫用户id : " + INXNIConstant.USER_OPEN_ID);
            long currentTimeMillis = System.currentTimeMillis();
            LogUtils.i("毫秒时间戳 : " + (beginTime - currentTimeMillis));
            if ((beginTime - currentTimeMillis) < 43200000) {
                SharedPrefsUtil.putValue(activity, "TMALL_ACCESS_TOKEN", "tmall_access_token", "");
                LogUtils.i("授权登录 INXNIConstant.USER_ID :" + INXNIConstant.USER_ID);
                AuthorizedLogin alogin = new AuthorizedLogin();
                alogin.setSceneCode(INXNIConstant.SCENE_CODE);
                alogin.setThirdUserType(INXNIConstant.THIRUSER_TYPE);
                alogin.setThirdUserIdentifier(INXNIConstant.USER_ID);//INXNIConstant.USER_ID INXNIConstant.THIRUSER_IDENTIFIER
                alogin.setAuthSource(authSource);
                aLi_interface.initialization("auth_login", alogin);
                //检测AccessToken
            } else {
                //就直接去鉴权 拿token
                INXNIConstant.ACCESS_TOKEN = mAccessToken;
                AuthorizedLogin authorizedLogin = new AuthorizedLogin();
                authorizedLogin.setAccessToken(INXNIConstant.ACCESS_TOKEN);
                authorizedLogin.setAuthSource(authSource);
                aLi_interface.initialization("authentication", authorizedLogin);
            }
        } else {
            LogUtils.i("INXNIConstant.USER_ID is null");
            handler.sendEmptyMessageDelayed(DeviceListHandler.MSG_REQUEST_TMALL_AUTH, 1500);
        }

    }

    private static class DeviceListHandler extends Handler {
        public static final int MSG_REQUEST_DEVICE_STATUS = 1;
        public static final int MSG_REQUEST_TMALL_AUTH = 2;
        SoftReference<DeviceFragment> softReference;

        public DeviceListHandler(DeviceFragment fragment) {
            softReference = new SoftReference<>(fragment);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            DeviceFragment deviceFragment = softReference.get();
            if (deviceFragment != null)
                if (msg.what == MSG_REQUEST_DEVICE_STATUS) {
                    deviceFragment.requestDeviceListStatus();
                } else if (msg.what == MSG_REQUEST_TMALL_AUTH) {
                    deviceFragment.checkTmallAccountIsValid("重复获取");
                }
        }
    }
}
